package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.service.StorageService;
import com.cskaoyan.service.StorageServiceImpl;
import com.cskaoyan.util.ResponseUtil;
import com.cskaoyan.util.URIUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author stone
 * @date 2023/03/19 21:00
 */
@WebServlet("/admin/storage/*")
@MultipartConfig
public class AdminStorageServlet extends HttpServlet {
    private StorageService storageService = new StorageServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String operation = URIUtil.getOperation(this.getClass(), request);
        switch (operation) {
            case "/create":
                create(request, response);
                break;
        }
    }

    private void create(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Part filePart = request.getPart("file");
        InputStream inputStream = filePart.getInputStream();
        String originFileName = filePart.getSubmittedFileName();
        MarketStorage marketStorage = storageService.store(inputStream, filePart.getSize(),
                filePart.getContentType(), originFileName);
        ResponseUtil.responseOkJsonVo(response,marketStorage);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
